package com.xuelang.pipeline.entry.common;

import com.xuelang.pipeline.client.common.result.ApiResult;
import com.xuelang.pipeline.client.common.vo.PipelineProperties;
import feign.*;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.slf4j.Slf4jLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClientsConfiguration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import java.util.List;

/**
 * feign 调用基础控制器
 *
 * @author xiwen.zxg
 * @since 2024/6/5
 */
@Component
@Import(FeignClientsConfiguration.class)
public abstract class DynamicFeignTemplate<T> {

    /**
     * feign编码器
     */
    @Autowired
    private Encoder encoder;
    /**
     * feign解码器
     */
    @Autowired
    private Decoder decoder;
    /**
     * 配置文件
     */
    @Autowired
    private PipelineProperties pipelineProperties;

    /**
     * feign服务接口
     */
    protected T feignService;
    /**
     * 集群配置信息
     */
    protected List<PipelineProperties.Cluster> workerClusterMapper;
    /**
     * 找不到集群配置信息
     *
     * @return
     */
    public ApiResult notFoundClusterConfigResult() {
        return ApiResult.fail("Worker服务配置中不存在该集群信息.");
    }

    /**
     * 初始化feign服务接口
     */
    @SuppressWarnings("all")
    @PostConstruct
    protected void initFeignService() {
        workerClusterMapper = pipelineProperties.getWorker().getClusters();
        Class<T> type = (Class<T>) ((java.lang.reflect.ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        feignService = Feign.builder()
                        .encoder(encoder)
                        .decoder(decoder)
                        .options(new Request.Options(3000, 3500))
                        .retryer(new Retryer.Default(1000, 1000, 1))
                        .logger(new Slf4jLogger(type))
                        .logLevel(Logger.Level.FULL)
                        // 注册feign
                        .target(Target.EmptyTarget.create(type));
    }


}
